package com.drinks.yiniang.ui.fragment.user;


import android.content.Intent;
import android.graphics.Typeface;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.home.RecommendsGoodsAdapter;
import com.drinks.yiniang.adapter.listview.UserServiceGridAdapter;
import com.drinks.yiniang.common.recycler.decoration.HomeGoodsItemDecoration;
import com.drinks.yiniang.entity.common.IconTextEntity;
import com.drinks.yiniang.entity.goods.GoodsJson;
import com.drinks.yiniang.entity.goods.RecommendGoodsJson;
import com.drinks.yiniang.entity.user.UserInfoJson;
import com.drinks.yiniang.io.api.GoodsApiIO;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.ui.activity.common.YNCaptureActivity;
import com.drinks.yiniang.ui.activity.community.CommunityNewsActivity;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.activity.message.MessageActivity;
import com.drinks.yiniang.ui.activity.shop.ShopListActivity;
import com.drinks.yiniang.ui.activity.user.UserDataActivity;
import com.drinks.yiniang.ui.activity.user.achievement.AchievementActivity;
import com.drinks.yiniang.ui.activity.community.MyCommentsActivity;
import com.drinks.yiniang.ui.activity.user.friends.MyFriendsActivity;
import com.drinks.yiniang.ui.activity.user.milepost.MilepostActivity;
import com.drinks.yiniang.ui.activity.user.order.MyOrderActivity;
import com.drinks.yiniang.ui.activity.user.points.CouponActivity;
import com.drinks.yiniang.ui.activity.user.points.PointsExchangeActivity;
import com.drinks.yiniang.ui.activity.user.setting.UserSettingActivity;
import com.drinks.yiniang.ui.activity.user.wallet.RechargeActivity;
import com.drinks.yiniang.ui.activity.user.wallet.WalletActivity;
import com.drinks.yiniang.ui.activity.user.wish.WishListActivity;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.drinks.yiniang.ui.widget.layout.FrameTvRedDotLayout;
import com.hansen.library.Constants;
import com.hansen.library.ui.fragment.BaseFragment;
import com.hansen.library.ui.widget.listview.NoScrollGridView;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.hansen.library.utils.ScreenSizeUtils;
import com.hansen.library.utils.StringUtils;
import com.hansen.zxinglibrary.zxing.integration.android.IntentIntegrator;;import java.util.ArrayList;
import java.util.List;

import static com.hansen.zxinglibrary.zxing.integration.android.IntentIntegrator.QR_CODE;

/**
 * 用户中心页面
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class UserCenterPageFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
        AppBarLayout.OnOffsetChangedListener, AdapterView.OnItemClickListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    private static final int REQ_WALLET_CODE = 0x01;//钱包
    private static final int REQ_RECHARGE_CODE = 0x02;//充值
    private static final int REQ_USER_DATA_CODE = 0x03;//个人资料

    private MSwipeRefreshLayout refresh_user_center;
    private AppBarLayout app_bar_ucenter;
    //设置
    private ImageView iv_ucenter_setting;
    //消息中心
    private ImageView iv_ucenter_msg;
    //头像
    private CircleImageView iv_ucenter_avatar;
    //扫码
    private ImageView iv_ucenter_scan_code;
    //昵称
    private TextView tv_ucenter_nickname;
    //等级
    private TextView tv_ucenter_level;
    //徽章
    private TextView tv_ucenter_badge;
    //积分
    private TextView tv_ucenter_points;
    //优惠券
    private TextView tv_ucenter_coupon;
    //门店优惠券
    private TextView tv_ucenter_shop_coupon;
    //-----订单
    //查看全部订单
    private TextView tv_ucenter_view_all_order;
    //待付款订单
    private FrameTvRedDotLayout fl_ucenter_wait_for_pay;
    //待发货
    private FrameTvRedDotLayout fl_ucenter_wait_for_deliver;
    //待收货
    private FrameTvRedDotLayout fl_ucenter_wait_for_receipt;
    //待评价
    private FrameTvRedDotLayout fl_ucenter_wait_for_evaluate;
    //日常购物推荐商品列表
    private BaseRecyclerView rcv_user_center;
    //常用服务列表
    private NoScrollGridView gv_ucenter_service;

    //服务
    private UserServiceGridAdapter mServiceGridAdapter;
    //商品
    private RecommendsGoodsAdapter mRecommendsGoodsAdapter;

    private SpannableStringBuilder mBuilder;
    private int sp20;

    public UserCenterPageFragment() {
        // Required empty public constructor
    }

    public static UserCenterPageFragment newInstance() {
        return new UserCenterPageFragment();
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_user_center_page;
    }

    @Override
    protected void initView(View mView) {
        refresh_user_center = mView.findViewById(R.id.refresh_user_center);

        app_bar_ucenter = mView.findViewById(R.id.app_bar_ucenter);

        iv_ucenter_setting = mView.findViewById(R.id.iv_ucenter_setting);
        iv_ucenter_msg = mView.findViewById(R.id.iv_ucenter_msg);
        iv_ucenter_avatar = mView.findViewById(R.id.iv_ucenter_avatar);
        iv_ucenter_scan_code = mView.findViewById(R.id.iv_ucenter_scan_code);

        tv_ucenter_nickname = mView.findViewById(R.id.tv_ucenter_nickname);
        tv_ucenter_level = mView.findViewById(R.id.tv_ucenter_level);
        tv_ucenter_badge = mView.findViewById(R.id.tv_ucenter_badge);
        tv_ucenter_points = mView.findViewById(R.id.tv_ucenter_points);
        tv_ucenter_coupon = mView.findViewById(R.id.tv_ucenter_coupon);
        tv_ucenter_shop_coupon = mView.findViewById(R.id.tv_ucenter_shop_coupon);
        tv_ucenter_view_all_order = mView.findViewById(R.id.tv_ucenter_view_all_order);

        fl_ucenter_wait_for_pay = mView.findViewById(R.id.fl_ucenter_wait_for_pay);
        fl_ucenter_wait_for_deliver = mView.findViewById(R.id.fl_ucenter_wait_for_deliver);
        fl_ucenter_wait_for_receipt = mView.findViewById(R.id.fl_ucenter_wait_for_receipt);
        fl_ucenter_wait_for_evaluate = mView.findViewById(R.id.fl_ucenter_wait_for_evaluate);

        gv_ucenter_service = mView.findViewById(R.id.gv_ucenter_service);

        rcv_user_center = mView.findViewById(R.id.rcv_user_center);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        mBuilder = new SpannableStringBuilder();

        sp20 = ScreenSizeUtils.sp2Px(mContext, 20);

        initUserData();

        initServiceAdapter();
        initGoodsAdapter();

        getUserInfo();
    }

    @Override
    protected void listener() {
        iv_ucenter_setting.setOnClickListener(this);
        iv_ucenter_msg.setOnClickListener(this);
        iv_ucenter_avatar.setOnClickListener(this);
        iv_ucenter_scan_code.setOnClickListener(this);
        tv_ucenter_badge.setOnClickListener(this);
        tv_ucenter_coupon.setOnClickListener(this);
        tv_ucenter_shop_coupon.setOnClickListener(this);
        tv_ucenter_view_all_order.setOnClickListener(this);
        fl_ucenter_wait_for_pay.setOnClickListener(this);
        fl_ucenter_wait_for_deliver.setOnClickListener(this);
        fl_ucenter_wait_for_receipt.setOnClickListener(this);
        fl_ucenter_wait_for_evaluate.setOnClickListener(this);

        refresh_user_center.setOnRefreshListener(this);

        app_bar_ucenter.addOnOffsetChangedListener(this);

        gv_ucenter_service.setOnItemClickListener(this);
        mRecommendsGoodsAdapter.setOnItemClickListener(this);
        mRecommendsGoodsAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void widgetClick(View v) {
        Intent mIntent;

        switch (v.getId()) {
            case R.id.iv_ucenter_setting://设置
                mIntent = new Intent(mContext, UserSettingActivity.class);
                startActivity(mIntent);
                break;
            case R.id.iv_ucenter_msg://消息中心
                mIntent = new Intent(mContext, MessageActivity.class);
                startActivity(mIntent);
                break;
            case R.id.iv_ucenter_avatar://头像用户资料
                mIntent = new Intent(mContext, UserDataActivity.class);
                startActivityForResult(mIntent, REQ_USER_DATA_CODE);
                break;
            case R.id.tv_ucenter_badge://成就
                mIntent = new Intent(mContext, AchievementActivity.class);
                startActivity(mIntent);
                break;
            case R.id.tv_ucenter_coupon: //优惠券
                mIntent = new Intent(mContext, CouponActivity.class);
                mIntent.putExtra(Constants.KeyType, Constants.TYPE_COUPON_COMMON);
                startActivity(mIntent);
                break;
            case R.id.tv_ucenter_shop_coupon://门店优惠券
                mIntent = new Intent(mContext, CouponActivity.class);
                mIntent.putExtra(Constants.KeyType, Constants.TYPE_COUPON_SHOP);
                startActivity(mIntent);
                break;
            case R.id.iv_ucenter_scan_code://扫码
                IntentIntegrator integrator = new IntentIntegrator(getActivity());
                integrator.setOrientationLocked(false);
                integrator.setDesiredBarcodeFormats(QR_CODE);
                integrator.setCaptureActivity(YNCaptureActivity.class);
                integrator.initiateScan();
                break;
            case R.id.tv_ucenter_view_all_order://全部订单
                mIntent = new Intent(mContext, MyOrderActivity.class);
                startActivity(mIntent);
                break;
            case R.id.fl_ucenter_wait_for_pay://待付款
                mIntent = new Intent(mContext, MyOrderActivity.class);
                mIntent.putExtra(Constants.KeyOrderType, Constants.TYPE_ORDER_WAIT_FOR_PAY);
                startActivity(mIntent);
                break;
            case R.id.fl_ucenter_wait_for_deliver://待发货
                mIntent = new Intent(mContext, MyOrderActivity.class);
                mIntent.putExtra(Constants.KeyOrderType, Constants.TYPE_ORDER_WAIT_FOR_DELIVER);
                startActivity(mIntent);
                break;
            case R.id.fl_ucenter_wait_for_receipt://待收货
                mIntent = new Intent(mContext, MyOrderActivity.class);
                mIntent.putExtra(Constants.KeyOrderType, Constants.TYPE_ORDER_WAIT_FOR_RECEIPT);
                startActivity(mIntent);
                break;
            case R.id.fl_ucenter_wait_for_evaluate://待评价
                mIntent = new Intent(mContext, MyOrderActivity.class);
                mIntent.putExtra(Constants.KeyOrderType, Constants.TYPE_ORDER_WAIT_FOR_EVALUATE);
                startActivity(mIntent);
                break;
            default:
                break;
        }
    }

    private void initServiceAdapter() {
        List<IconTextEntity> list = new ArrayList<>();

        IconTextEntity entity = new IconTextEntity(R.mipmap.icon_my_wallet, getString(R.string.text_my_wallet));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_recharge, getString(R.string.text_recharge));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_shop_details, getString(R.string.text_shop_list));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_milepost, getString(R.string.text_milepost));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_community_news, getString(R.string.text_community_news));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_my_friends, getString(R.string.text_my_friends));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_wish_list, getString(R.string.text_wish_list));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_my_options, getString(R.string.text_my_evaluate));
        list.add(entity);
        entity = new IconTextEntity(R.mipmap.icon_points_exchange, getString(R.string.text_points_exchange));
        list.add(entity);

        mServiceGridAdapter = new UserServiceGridAdapter(mContext, list);

        gv_ucenter_service.setAdapter(mServiceGridAdapter);
    }

    private void initGoodsAdapter() {
        rcv_user_center.setLayoutManager(RecyclerUtils.getVerticalGridLayout(mContext, 2));
        rcv_user_center.addItemDecoration(HomeGoodsItemDecoration.getItemDPDecoration(10));

        mRecommendsGoodsAdapter = new RecommendsGoodsAdapter(mContext, new ArrayList<GoodsJson.GoodsList>());
        mRecommendsGoodsAdapter.setCommonEmpty(getLayoutInflater(), rcv_user_center);
        mRecommendsGoodsAdapter.bindToRecyclerView(rcv_user_center);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset >= 0) {
            refresh_user_center.setEnabled(true);
        } else {
            refresh_user_center.setEnabled(false);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent mIntent;

        switch (position) {
            case 0://钱包
                mIntent = new Intent(mContext, WalletActivity.class);
                startActivityForResult(mIntent, REQ_WALLET_CODE);
                break;
            case 1://充值
                mIntent = new Intent(mContext, RechargeActivity.class);
                startActivityForResult(mIntent, REQ_RECHARGE_CODE);
                break;
            case 2://门店详情
                mIntent = new Intent(mContext, ShopListActivity.class);
                startActivity(mIntent);
                break;
            case 3://里程碑
                mIntent = new Intent(mContext, MilepostActivity.class);
                startActivity(mIntent);
                break;
            case 4://社区动态
                mIntent = new Intent(mContext, CommunityNewsActivity.class);
                startActivity(mIntent);
                break;
            case 5://我的好友
                mIntent = new Intent(mContext, MyFriendsActivity.class);
                startActivity(mIntent);
                break;
            case 6://心愿单
                mIntent = new Intent(mContext, WishListActivity.class);
                startActivity(mIntent);
                break;
            case 7://我的点评
                mIntent = new Intent(mContext, MyCommentsActivity.class);
                startActivity(mIntent);
                break;
            case 8://积分兑换
                mIntent = new Intent(mContext, PointsExchangeActivity.class);
                startActivity(mIntent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constants.RESULT_CODE_NORMAL) {
            switch (requestCode) {
                case REQ_WALLET_CODE://钱包页返回
                case REQ_RECHARGE_CODE://充值页返回
                case REQ_USER_DATA_CODE://个人资料修改
                    getUserInfo();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        GoodsJson.GoodsList data = mRecommendsGoodsAdapter.getItem(position);

        if(data == null) {
            return;
        }

        Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
        intent.putExtra(Constants.KeyGoodsId, data.getId());
        startActivity(intent);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        GoodsJson.GoodsList data = mRecommendsGoodsAdapter.getItem(position);

        if(data == null) {
            return;
        }

        if(view.getId() == R.id.iv_home_goods_add_cart) addToCart(data.getId());
    }

    @Override
    public void onRefresh() {
        getUserInfo();
    }

    private void addToCart(String goodsId) {
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取推荐列表
    private void getRecommend() {
        GoodsApiIO.getInstance().getRecommendGoodsList(new APIRequestCallback<RecommendGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(RecommendGoodsJson res) {
                if (mRecommendsGoodsAdapter == null) {
                    return;
                }

                mRecommendsGoodsAdapter.getData().clear();
                mRecommendsGoodsAdapter.addData(res.getData());
                mRecommendsGoodsAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                mRecommendsGoodsAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getUserInfo() {
        if (!refresh_user_center.isRefreshing()) {
            showLoadingDialog();
        }

        UserApiIO.getInstance().getUserInfo(new APIRequestCallback<UserInfoJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UserInfoJson res) {
                setUserData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                refresh_user_center.setRefreshing(false);
                dismissDialog();
                getRecommend();
            }
        });
    }

    private void setUserData(UserInfoJson.UserInfoData data) {
        int start, end;

        GlideUtils.loadAvatar(this, iv_ucenter_avatar, data.getAvatar());

        //昵称
        tv_ucenter_nickname.setText(StringUtils.getNullEmptyConvert__(data.getUsername()));
        //等级
        tv_ucenter_level.setText("LV." + StringUtils.getNullEmptyConvertZero(data.getLevel()));
        //徽章数量
        tv_ucenter_badge.setText(StringUtils.getNullEmptyConvertZero("0") + "徽章");
        //积分
        mBuilder.clearSpans();
        mBuilder.clear();
        start = 0;
        mBuilder.append(StringUtils.getNullEmptyConvertZero(data.getPoints()));
        end = mBuilder.length();
        mBuilder.append("\n");
        mBuilder.append(getString(R.string.text_points));
        mBuilder.setSpan(new AbsoluteSizeSpan(sp20), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mBuilder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_ucenter_points.setText(mBuilder);
        //优惠券
        mBuilder.clearSpans();
        mBuilder.clear();
        start = 0;
        mBuilder.append(StringUtils.getNullEmptyConvertZero(data.getCoupons_count()));
        end = mBuilder.length();
        mBuilder.append("\n");
        mBuilder.append(getString(R.string.text_coupon));
        mBuilder.setSpan(new AbsoluteSizeSpan(sp20), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mBuilder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_ucenter_coupon.setText(mBuilder);
        //门店优惠券
        mBuilder.clearSpans();
        mBuilder.clear();
        start = 0;
        mBuilder.append(StringUtils.getNullEmptyConvertZero(data.getStores_coupons_count()));
        end = mBuilder.length();
        mBuilder.append("\n");
        mBuilder.append(getString(R.string.text_shop_coupon));
        mBuilder.setSpan(new AbsoluteSizeSpan(sp20), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mBuilder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_ucenter_shop_coupon.setText(mBuilder);

        if (data.getOrders() != null) {//订单未处理数量
            //待付款
            fl_ucenter_wait_for_pay.setRedNumText(data.getOrders().getWait_pay());
            //待发货
            fl_ucenter_wait_for_deliver.setRedNumText(data.getOrders().getWait_deliver());
            //待收货
            fl_ucenter_wait_for_receipt.setRedNumText(data.getOrders().getWait_receipt());
            //待评价
            fl_ucenter_wait_for_evaluate.setRedNumText(data.getOrders().getWait_evaluate());
        }
    }

    private void initUserData() {
        int start, end;

        //积分
        mBuilder.clearSpans();
        mBuilder.clear();
        start = 0;
        mBuilder.append("0");
        end = mBuilder.length();
        mBuilder.append("\n");
        mBuilder.append(getString(R.string.text_points));
        mBuilder.setSpan(new AbsoluteSizeSpan(sp20), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mBuilder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_ucenter_points.setText(mBuilder);
        //优惠券
        mBuilder.clearSpans();
        mBuilder.clear();
        start = 0;
        mBuilder.append("0");
        end = mBuilder.length();
        mBuilder.append("\n");
        mBuilder.append(getString(R.string.text_coupon));
        mBuilder.setSpan(new AbsoluteSizeSpan(sp20), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mBuilder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_ucenter_coupon.setText(mBuilder);
        //门店优惠券
        mBuilder.clearSpans();
        mBuilder.clear();
        start = 0;
        mBuilder.append("0");
        end = mBuilder.length();
        mBuilder.append("\n");
        mBuilder.append(getString(R.string.text_shop_coupon));
        mBuilder.setSpan(new AbsoluteSizeSpan(sp20), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        mBuilder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_ucenter_shop_coupon.setText(mBuilder);
    }
}
